package com.wmyg.tracker.dao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.wmyg.tracker.bean.*;
import com.wmyg.tracker.sdk.FabricResult;
import com.wmyg.tracker.sdk.SmartManager;
import com.wmyg.tracker.sdk.UltimateManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Slf4j
@Repository
public class FabricDao {

    @Autowired
    UltimateManager smartManager;

    public QRInfo query(String qR, QueryInfo queryInfo) throws Throwable {
        String[] args = new String[]{qR, queryInfo.getAddressInfo().getAddressDetail(), queryInfo.getQueryTime(),
                queryInfo.getUserAgent(), Float.toString(queryInfo.getAddressInfo().getCoordinates()[0]),
        Float.toString(queryInfo.getAddressInfo().getCoordinates()[1]), queryInfo.getAddressInfo().getIpAddress(),
        queryInfo.getAppUserId()};
        log.info("Track by args {}--------------------------------------------", Arrays.toString(args));
//        SmartManager smartManager = ManageBuilder.buildManagerToUse("south", "User1", "antifake", "developchannel");
        FabricResult map = null;
        if (qR.substring(22, 28).matches("\\d+")) {
            map = smartManager.invoke("queryQRInfoCompressedNew", args);
        } else if (Integer.parseInt(qR.substring(33, 39)) < 180218) {
            map = smartManager.invoke("queryQRInfo", args);
        } else {
            map = smartManager.invoke("queryQRInfoCompressed", args);
        }
        if (map.getCode() == 0) {
            log.info("Query Success for QR: " + qR);
        }
        log.info("qrInfo json is {}", map.getData());
        QRInfo qrInfo = JSON.parseObject(map.getData(), QRInfo.class);
        int size = 0;
        if (null != qrInfo.getQueryHistory()) {
            size = qrInfo.getQueryHistory().size();
        }
        log.info("This qr {} is queried for {} times, this result is from chaincode------------------------------------------",qR , size);
        return qrInfo;
//        return null;
    }
}
